<template>
  <Layout :style="zoomStyle" class="main">
    <Sider
      hide-trigger
      collapsible
      :width="226"
      :collapsed-width="64"
      v-model="collapsed"
      class="left-sider"
      :style="{overflow: 'hidden'}"
    >
      <side-menu
        accordion
        ref="sideMenu"
        :active-name="$route.name"
        :collapsed="collapsed"
        @on-select="turnToPage"
        :menu-list="menuList"
      >
        <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
        <template v-slot:logo>
          <div class="logo-con">
            <img class="max-logo" v-show="!collapsed" :src="maxLogo" key="max-logo">
            <img class="min-logo" v-show="collapsed" :src="minLogo" key="min-logo">
          </div>
          <div class="h-1px"></div>
        </template>
        <!-- <template v-slot:user>
          <div class="menu-user">
            <Avatar :src="userAvator" size="large"/>
            <div class="name">{{userName}}</div>
          </div>
        </template>-->
      </side-menu>
    </Sider>
    <Layout>
      <Header class="header-con">
        <header-bar
          :collapsed="collapsed"
          :loading="loading"
          :hasAxs="hasAxs"
          :msgCount="msgCount"
          @on-coll-change="handleCollapsedChange"
          @ax-login="axLogin"
          @open-drawer="drawerShowFn"
        >
          <user
            :message-unread-count="unreadCount"
            :user-avator="userAvator"
            :user-name="userName"
          />
          <!-- <Dropdown class="mr-30 pull-right">
            <Badge :count="3">
              <Icon type="ios-notifications-outline" :size="36" class="msg-icon"/>
            </Badge>
            <DropdownMenu slot="list">
              <DropdownItem>邮件</DropdownItem>
            </DropdownMenu>
          </Dropdown> -->
          <!-- <language v-if="$config.useI18n" @on-lang-change="setLocal" style="margin-right: 10px;" :lang="local"/> -->
          <!-- <error-store v-if="$config.plugin['error-store'] && $config.plugin['error-store'].showInHeader" :has-read="hasReadErrorPage" :count="errorCount"></error-store> -->

          <!-- <fullscreen v-model="isFullscreen" style="margin-right: 10px;"/> -->
        </header-bar>
      </Header>
      <Content class="main-content-con">
        <Layout class="main-layout-con">
          <div class="tag-nav-wrapper">
            <tags-nav
              :value="$route"
              @input="handleClick"
              :list="tagNavList"
              @on-close="handleCloseTag"
            />
          </div>
          <Content class="content-wrapper pall-0">
            <!-- <keep-alive :include="cacheList"> -->
            <keep-alive>
              <router-view v-if="$route.meta.keepAlive"/>
            </keep-alive>
            <router-view v-if="!$route.meta.keepAlive"/>
            <ABackTop :height="100" :bottom="80" :right="50" container=".content-wrapper"></ABackTop>
            <Drawer class="msg-drawer" title="未读消息" :closable="false" v-model="drawerShow">
              <List>
                <div v-for="item in msgData" @click="readMsg(item.BusinessModule)" :key="item.ID">
                  <ListItem>
                    <ListItemMeta>
                      <div slot="title">{{item.Title}} - {{item.Message}}</div>
                      <div slot="description" style="font-size:12px">
                        <Icon class="mr" type="md-time" size="14"/>
                        {{sendTime(item.CreateTime)}}
                      </div>
                    </ListItemMeta>
                  </ListItem>
                </div>
              </List>
            </Drawer>
          </Content>
        </Layout>
      </Content>
    </Layout>
  </Layout>
</template>
<script>
import Cookies from "js-cookie";
import anxinApi from "@/api/anxin.api.js";
import SideMenu from "./components/side-menu";
import HeaderBar from "./components/header-bar";
import TagsNav from "./components/tags-nav";
import User from "./components/user";
import ABackTop from "./components/a-back-top";
import Fullscreen from "./components/fullscreen";
import Language from "./components/language";
import ErrorStore from "./components/error-store";
import { mapMutations, mapActions, mapGetters } from "vuex";
import { getNewTagList, routeEqual } from "@/libs/util";
import routers from "@/router/routers";
import minLogo from "@/assets/images/Logo_collapsed.png";
import maxLogo from "@/assets/images/Logo_open.png";
import "./main.less";

import config from '@/config'
const wsUrl = process.env.NODE_ENV === 'development' ? config.wsUrl.dev : config.wsUrl.pro

export default {
  name: "Main",
  components: {
    SideMenu,
    HeaderBar,
    Language,
    TagsNav,
    Fullscreen,
    ErrorStore,
    User,
    ABackTop
  },
  data() {
    return {
      timer: null,
      loading: false,
      collapsed: false,
      minLogo,
      maxLogo,
      isFullscreen: false,
      currentRouteName: null,
      zoomStyle: {
        height: "100%"
      },
      hasAxs: false, // 是否存在安薪税按钮
      msgShow: true,
      handlerUrl: wsUrl,
      webSocket: null,
      msgData: [],
      drawerShow: false
    };
  },
  computed: {
    ...mapGetters(["errorCount"]),
    tagNavList() {
      return this.$store.state.app.tagNavList;
    },
    tagRouter() {
      return this.$store.state.app.tagRouter;
    },
    userAvator() {
      return this.$store.state.user.avatorImgPath;
    },
    userName() {
      return this.$store.state.user.userName;
    },
    cacheList() {
      const list = [
        "ParentView",
        ...(this.tagNavList.length
          ? this.tagNavList
              .filter(item => !(item.meta && item.meta.notCache))
              .map(item => item.name)
          : [])
      ];
      return list;
    },
    menuList() {
      return this.$store.getters.menuList;
    },
    local() {
      return this.$store.state.app.local;
    },
    hasReadErrorPage() {
      return this.$store.state.app.hasReadErrorPage;
    },
    unreadCount() {
      return this.$store.state.user.unreadCount;
    },
    msgCount() {
      console.log(this.msgData)
      return this.msgData.length
    },
    sendTime () {
      return (time) => {
        if (time) {
          let date;
          let m2=this.$moment();  //当下时间
          let m1=this.$moment(time);
          let du = this.$moment.duration(m2 - m1, 'ms');   //做差
          let days = du.get('days');
          let hours = du.get('hours');
          let mins = du.get('minutes');   
          let ss = du.get('seconds'); 
          // console.log(days,hours,mins,ss)
          if (days>0) {
            date=this.$moment(time).format("YYYY年MM月DD日");
            return date
          }else if(hours>0){
            return hours+'小时前'
          }else{
            return mins+'分钟前'
          }
        } else {
          return ''
        }
      }
    },
  },
  methods: {
    ...mapMutations([
      "setBreadCrumb",
      "setTagNavList",
      "addTag",
      "setLocal",
      "setHomeRoute",
      "closeTag"
    ]),
    ...mapActions(["handleLogin", "getUnreadMessageCount"]),
    turnToPage(route) {
      let { name, params, query } = {};
      if (typeof route === "string") name = route;
      else {
        name = route.name;
        params = route.params;
        query = route.query;
      }
      if (name.indexOf("isTurnByHref_") > -1) {
        window.open(name.split("_")[1]);
        return;
      }
      this.$router.push({
        name,
        params,
        query
      });
    },
    handleCollapsedChange(state) {
      this.collapsed = state;
    },
    handleCloseTag(res, type, route) {
      if (type !== "others") {
        if (type === "all") {
          this.turnToPage(this.$config.homeName);
        } else {
          if (routeEqual(this.$route, route)) {
            this.closeTag(route);
          }
        }
      }
      this.setTagNavList(res);
    },
    handleClick(item) {
      this.turnToPage(item);
    },
    // handleChangeZoom (ratio) {
    //   console.log('🆗 ratio: ', ratio)
    //   Cookies.set('changeRatio', JSON.stringify(ratio))
    //   this.zoomStyle = {
    //     height: '100%',
    //     zoom: ratio + '%'
    //   }
    // },
    axLogin() {
      this.loading = true;
      anxinApi.axsLogin().then(res => {
        this.loading = false;
        if (res.data.success) {
          window.open(res.data.data, "_blank");
        }
      });
    },
    getEnum() {
      let groupNames = "system.config";
      anxinApi
        .getEnum({
          groupName: groupNames
        })
        .then(res => {
          let arr = this.getItems(res.data, "system.config");
          let obj = arr.find(item => {
            return item.key === "axsenableswitch";
          });
          if (obj.value === "1") {
            this.hasAxs = true;
          } else {
            this.hasAxs = false;
          }
        });
    },
    getItems(arr, key) {
      let object = arr.find(item => {
        return item.group === key;
      });
      return object.items;
    },

    // 长连接
    InitWebSocket() {
      //如果WebSocket对象未初始化，我们将初始化它
      this.webSocket = null
      if (!this.webSocket) {
        let socket = new WebSocket(this.handlerUrl + '/' + this.$store.state.user.userId);
        console.log('%%%%%%%%%%%%%%%%%%%%%%%%')
        this.webSocket = socket
        console.log(this.$store.state.user.userId)

        //打开连接处理程序
        this.webSocket.onopen = () => {
          // this.msgShow = true
          console.log('链接成功')
          console.log(this.webSocket)
        };

        //消息数据处理程序
        this.webSocket.onmessage = (e) => {
          console.log(this.webSocket)
          console.log('🙃🙃🙃🙃🙃🙃🙃')
          console.log(e.data)
          let obj = JSON.parse(e.data)
          switch (obj.Type) {
            case 'new':
              this.msgData = obj.Msg
              break;
            case 'add':
              this.msgData = this.msgData.concat(obj.Msg)
              break;
            case 'remove':
              this.msgData = obj.Msg
              break;
            default:
              break;
          }
        };

        //关闭事件处理程序
        this.webSocket.onclose = () => {
          console.log("断线了 ");
        };

        //错误事件处理程序
        this.webSocket.onerror = (e) => {
          console.log("链接失败:" + e);
        };
      } else {
        console.log('^^^^^^^^^^^^^^^^^^^^^^^^^^')
        // webSocket.open();没有open方法
      }
    },
    drawerShowFn () {
      this.drawerShow = true
    },
    readMsg (code) {
      console.log(44444444444)
      let arr = []
      this.msgData.forEach(item => {
        if (item.BusinessModule === code) arr.push(item.ID)
      })
      this.drawerShow = false
      this.webSocket.send(arr.join(','))
      this.$router.push({ name: code })
    }
  },
  watch: {
    $route(newRoute) {
      const { name, query, params, meta } = newRoute;
      this.addTag({
        route: { name, query, params, meta },
        type: "push"
      });
      this.setBreadCrumb(newRoute);
      this.setTagNavList(getNewTagList(this.tagNavList, newRoute));
      this.$refs.sideMenu.updateOpenName(newRoute.name);
    },
  },
  mounted() {
    this.currentRouteName = this.$route.name;
    /**
     * @description 初始化设置面包屑导航和标签导航
     */
    console.log(this.$store.state.user.avatorImgPath);
    this.setTagNavList();
    this.setHomeRoute(routers);
    const { name, params, query, meta } = this.$route;
    this.addTag({
      route: { name, params, query, meta }
    });
    this.setBreadCrumb(this.$route);
    // 设置初始语言
    this.setLocal(this.$i18n.locale);
    // 如果当前打开页面不在标签栏中，跳到homeName页
    if (!this.tagNavList.find(item => item.name === this.$route.name)) {
      this.$router.push({
        name: this.$config.homeName
      });
    }
    this.getEnum();
    // 获取未读消息条数
    // let that = this
    // this.InitWebSocket()
    // this.timer = setInterval(() => {
    //   if (that.webSocket.readyState == 3) {
    //     this.InitWebSocket()
    //   }
    // }, 5000);
    // this.getUnreadMessageCount()

    // const cookieRatio = Cookies.get('changeRatio')
    // if (cookieRatio) {
    //   var num = cookieRatio.replace(/[^0-9]/ig, '')
    //   this.handleChangeZoom(num)
    // }
  }
};
</script>
<style lang="less" scoped>
  .msg-icon{
    margin-top: 8px;
  }
  .msg-drawer{
    /deep/ .ivu-drawer-body{
      padding-top: 0;
      padding-bottom: 0;
      height: calc(85%);
      .ivu-list-items{
        cursor: pointer;
        .ivu-list-item-meta-title{
          color: #333;
        }
      }
      .ivu-list-split .ivu-list-item:last-child{
        border-bottom: 1px solid #e8eaec !important;

      }
    }
  }
</style>

